<template>
  <div class="star-box">
    <div
      class="star-item"
      :class="{ active: item === 1 }"
      @click="changeLevel(index)"
      v-for="(item, index) in starList"
      :key="index"
    ></div>
  </div>
</template>
<script setup>
import { ref,watch } from "vue";

const props = defineProps({
  level: {
    type: Number,
    default: 0,
  },
  canEdit: {
    type: Boolean,
    default: false,
  },
});

const starList = ref([]);
const emits = defineEmits(["change"]);

watch(
  () => props.level,
  (newVal) => {
    for (let i = 0; i < 5; i++) {
      starList.value[i] = i < newVal ? 1 : 0;
    }
  },
  {
    immediate: true,
  }
);

const changeLevel = (index) => {
  if (!props.canEdit) {
    return;
  }
  // 取消选中某一项(不包括最后一项)
  if(starList.value[index] === 1 && starList.value[index + 1] === 0) {
    starList.value[index] = 0;
    emits("change", index);
    return;
  } else if(index === 4 && starList.value[index] === 1){
    // 取消选中最后一项
    starList.value[index] = 0;
    emits("change", index);
    return;
  }
  // 选中某一项
  for (let i = 0; i <= index; i++) {
    starList.value[i] = 1;
  }
  for (let i = index + 1; i < 5; i++) {
    starList.value[i] = 0;
  }
  emits("change", index + 1);
};
</script>
<style scoped>
.star-box {
  display: flex;
  align-items: center;
  column-gap: 15px;
}
.star-item {
  width: 31px;
  height: 31px;
  background-size: 100% 100%;
  background-image: url("../assets/image/star-grey.png");
  cursor: pointer;
}
.star-item.active {
  background-image: url("../assets/image/star.png");
}
</style>
